/**
 * Copyright 2008 ts Inc.
 */
package net.wicp.tams.common.agent;

import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;

import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.DynamicType.Builder;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.This;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;

/**
 * aaaaa.
 * 
 * @author Administrator
 *
 */
@Slf4j
public class AgentMain {
	@RuntimeType
	public Object intercept(@This Object obj, @AllArguments Object[] allArguments, @Origin Method method)
			throws Throwable {
		return null;
	}

	public static void premain(String arguments, Instrumentation instrumentation) {
		log.info("this is an perform monitor agent.");
		AgentBuilder.Transformer transformer = new AgentBuilder.Transformer() {
			@Override
			public Builder<?> transform(Builder<?> builder,
					net.bytebuddy.description.type.TypeDescription typeDescription, ClassLoader classLoader,
					JavaModule module) {
				return builder.method(ElementMatchers.<MethodDescription>any()) // 拦截任意方法
						.intercept(MethodDelegation.to(TimeInterceptor.class)); // 委托
			}
		};
		new AgentBuilder.Default().type(ElementMatchers.nameStartsWith("net.wicp.tams.app.demo.simple")) // 指定需要拦截的类ffffffffffffffffffffffffffffffffffffffffffff
				.transform(transformer).with(new AgentBuilder.Listener() {

					@Override
					public void onTransformation(net.bytebuddy.description.type.TypeDescription typeDescription,
							ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
						// log.info("onTransformation");

					}

					@Override
					public void onIgnored(net.bytebuddy.description.type.TypeDescription typeDescription,
							ClassLoader classLoader, JavaModule module, boolean loaded) {
						// log.info("onIgnored");

					}

					@Override
					public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded,
							Throwable throwable) {
						// log.info("onError");

					}

					@Override
					public void onComplete(String typeName, ClassLoader classLoader, JavaModule module,
							boolean loaded) {
						// log.info("onComplete");

					}

					@Override
					public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module,
							boolean loaded) {
						// log.info("onDiscovery");

					}
				}).installOn(instrumentation);
	}
}
